package com.example.demo.mq;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.inject.Provider;
import java.util.UUID;

/**
 * @author ghl
 * @version 1.0
 * @date 2022/9/19 10:34
 * @description 摘要
 */
@Component
public class RabbitServiceImpl implements RabbitService {

    private static Logger log = LoggerFactory.getLogger(RabbitServiceImpl.class);


    @Autowired
    private Provider<RabbitTemplate> provider;

    public RabbitTemplate getRabbitTemplate() {
        return provider.get();
    }


    @Override
    public String sendMessage(String routingKey, Object message) {
        String id = UUID.randomUUID().toString();
        CorrelationData correlationId = new CorrelationData(id);
        getRabbitTemplate().convertAndSend(routingKey, message, correlationId);
        log.info("发送Mq,路由键[{}],入参[{}]", routingKey, JSON.toJSONString(message));
        return id;
    }

    @Override
    public String sendMessage(String exchange, String routingKey, Object message) {
        String id = UUID.randomUUID().toString();
        CorrelationData correlationId = new CorrelationData(id);
        try {

            getRabbitTemplate().convertAndSend(exchange, routingKey, message, correlationId);
        }catch (Exception e){
            e.printStackTrace();
        }
        log.info("发送Mq,交换机[{}],路由键[{}],入参[{}]", exchange, routingKey, JSON.toJSONString(message));
        return id;
    }

    @Override
    public String sendDelayedMessage(String exchange, String routingKey, Object message, int delay) {
        String id = UUID.randomUUID().toString();
        CorrelationData correlationId = new CorrelationData(id);
        getRabbitTemplate().convertAndSend(exchange, routingKey, message, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message msg) throws AmqpException {
                msg.getMessageProperties().setDelay(delay);
                log.info("发送延迟[{}]ms 的Mq,交换机[{}],路由键[{}],入参[{}]", delay, exchange, routingKey, JSON.toJSONString(message));
                return msg;
            }
        }, correlationId);
        return id;
    }
}
